package com.ls.fw.data.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;

/**
 * 文件工具类
 * FileUtil.java
 * @author Defender
 * 2013-7-10 下午07:24:43
 */
public class FileUtil {

	 public static final String UTF8 = "utf-8";
	 public static final int BUFFER_SIZE = 1024;
	 public static final String separator = File.separator;
	 
	 
	 public static void main(String[] args) throws Exception {
		 String path = "E:\\java\\tt\\test\\";
		 System.out.println(FileUtil.createDir(path));
		 System.out.println(FileUtil.createDir(path+"dd"));
		 System.out.println(FileUtil.alterSeparator(path));
		 String filePath = path+"test.txt";
		 System.out.println(FileUtil.getFileName(filePath));
		 System.out.println(FileUtil.getParentPath(filePath));
		 System.out.println(FileUtil.createFile(filePath));
		 System.out.println(FileUtil.createFile(path+"dd\\t.txt"));
		 System.out.println(FileUtil.createFile(path+"dd\\t1.txt"));
		 //String []files = {filePath,path+"test1.txt",path+"dd"};
		  //System.out.println(FileUtil.delete(files));
		 //System.out.println(FileUtil.delete("E:\\java\\tt"));
		 //FileUtil.renameFile(path+"dd", "rename.txt");
		 FileUtil.writeFile(filePath, "content");
		 System.out.println(FileUtil.readFile(filePath));
		 
		 copyDirectiory(path,"E:\\java\\tt\\test1\\");
		 System.out.println(FileUtil.copyTo(path+"test.txt", "E:\\java\\tt\\test2\\"));
		 System.out.println(FileUtil.getExt(filePath));
	 }
	  


	public static boolean save(InputStream in, String fileName) {
		boolean flag = false;
		File outFile = new File(fileName);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(outFile);
			byte[] temp = new byte[BUFFER_SIZE];
			int length = -1;
			while ((length = in.read(temp)) > 0)
				out.write(temp, 0, length);
			out.flush();
			flag = true;
		} catch (Exception e) {
			System.out.println(e);
			flag = false;
		}finally{
			FileUtil.close(out);
		}
		return flag;
	}
	
	/**
	 * 读取文件
	 * @param file
	 * @return
	 */
	public static String readFile(File file){
		return readFile(file,UTF8);
	}
	/**
	 * 读取文件
	 * @param file
	 * @return
	 */
	public static String readFile(File file,String encode){
		String output = "";

		if (file.exists()) {
			if (file.isFile()) {
				BufferedReader input = null;
				try {
					InputStreamReader isr=new InputStreamReader(new FileInputStream(file),encode);
				    input = new BufferedReader(isr);
					StringBuffer buffer = new StringBuffer();
					String text;
					while ((text = input.readLine()) != null){
						buffer.append(text);
					}
					output = buffer.toString();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					FileUtil.close(input);
				}
			} else if (file.isDirectory()) {
				String[] dir = file.list();
				output += "Directory contents：\n";
				for (int i = 0; i < dir.length; i++) {
					output += dir[i] + "\n";
				}
			}
		} else {
			System.err.println("Does not exist！");
		}

		return output;
	}
	/**
	 * 读取文件
	 * @param filePath
	 * @return
	 */
	public static String readFile(String filePath,String encode) {
		File file = new File(filePath);
		return readFile(file,encode);
	}
	/**
	 * 读取文件
	 * @param filePath
	 * @return
	 */
	public static String readFile(String filePath) {
		return readFile(filePath,UTF8);
	}

		
	/**
	 * 写文件 
	 * @param f
	 * @param content
	 */
	public static void writeFile(File f,String content){
		  writeFile(f, content,UTF8);
	}
	/**
	 * 写文件 
	 * @param f
	 * @param content
	 */
	public static void writeFile(File f,String content,String encode){
		  BufferedWriter output = null;
		  try {
			   if (!f.exists()) {
			       f.createNewFile();
			   }
			   OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f),encode);
			   output = new BufferedWriter(osw);
			   output.write(content);
			   output.flush();
		  } catch (Exception e) {
		      e.printStackTrace();
		  }finally{
			  FileUtil.close(output);
		  }
	}
	/**
	 * 写文件
	 * @param path
	 * @param content
	 */
	public static void writeFile(String path, String content,String encode) {
	       File f = new File(path);
	       writeFile(f, content,encode);
	}
	/**
	 * 写文件
	 * @param path
	 * @param content
	 */
	public static void writeFile(String path, String content) {
	       File f = new File(path);
	       writeFile(f, content,UTF8);
	}

   /**
     * 文件重命名
     * @param path 文件目录
     * @param oldname 原来的文件名
     * @param newname 新文件名
     */
    public static void renameFile(String path,String oldname,String newname) throws Exception {
    	boolean flag = isExistsDir(path);
    	if(flag){
    		//新的文件名和以前文件名不同时,才有必要进行重命名
        	if(!oldname.equals(newname)){
        		File oldfile = new File(path + separator + oldname);
        		File newfile = new File(path + separator + newname);
        		//若在该目录下已经有一个文件和新文件名相同，则不允许重命名
        		if(newfile.exists()){
        			throw new Exception("该文件名已不存在!");
        		}else{
        			oldfile.renameTo(newfile);
        		}
        	} else {
        		throw new Exception("新文件名与原文件名相同,无法重命名!");
        	}
    	} else {
    		throw new Exception("该文件所在目录已不存在!");
    	}
    }
	 
    
    /**
     * 文件重命名
     * @author Defender
     * 2013-7-10 下午09:38:01
     * @param filePath
     * @param newname
     * @throws Exception
     */
    public static void renameFile(String filePath,String newname) throws Exception {
    	 renameFile(getParentPath(filePath),getFileName(filePath),newname);
    }
    
    
	/**
	 * 判断文件是否存在
	 * @author Defender
	 * 2013-7-7 上午10:45:44
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static boolean isExistsFile(String filePath) throws Exception {
		boolean flag = false;
		File file = new File(FileUtil.alterSeparator(filePath));
		// 如果目录存在
		if(file.isFile()&&file.exists()){
			flag = true;
		}
		return flag;
	} 
	
	/**
	 * 判断目录是否存在
	 * @param path
	 * @return
	 */
	public static boolean isExistsDir(String path) throws Exception {
		boolean flag = false;
		File dir = new File(FileUtil.alterSeparator(path));
		// 如果目录存在
		if(dir.isDirectory()&&dir.exists()){
			flag = true;
		}
		return flag;
	} 
	
	/**
	 * 创建文件夹
	 * @param path 目录
	 */
	public static boolean createDir(String path) throws Exception {
		boolean flag = isExistsDir(path);
		if(!flag){
			File dir = new File(FileUtil.alterSeparator(path));
			if(!dir.exists()){
				flag = dir.mkdirs();
			}
		}   
		return flag;
	}
	
	
	/**
	 * 修改文件路径的分隔符
	 * @author Defender
	 * 2013-7-10 下午07:59:37
	 * @param path
	 * @return
	 */
	public static String alterSeparator(String path){
		String dest = "";
		dest = path.replace("\\", separator);
		dest = dest.replace("/", separator);
		return dest;
	}
	
	
	/**
	 * 创建新文件
	 * @param path 目录
	 * @param filename 文件名
	 * @throws IOException 
	 */
    public static boolean createFile(String parentPath,String filename) throws Exception {
    	boolean flag = isExistsDir(parentPath);
    	if(!flag){
    		flag = createDir(parentPath);
    	}
    	if(flag){
    		String destDirPath = FileUtil.alterSeparator(parentPath);
    		if (!destDirPath.endsWith(separator)) {
    			 destDirPath = destDirPath + separator;
            }
    		File file = new File(destDirPath+filename);
            if(!file.exists()){
            	// 创建文件
            	flag = file.createNewFile();
            }
    	}else{
    		throw new Exception(parentPath+",对不起,该目录不存在!");
    	}
        return flag;
    }
    
    /**
     * 获取文件路径的父目录
     * @author Defender
     * 2013-7-10 下午08:14:13
     * @param filePath
     * @return
     */
    public static String getParentPath(String filePath){
    	int index = filePath.lastIndexOf(separator);
    	if(index>0){
    		return filePath.substring(0,index);
    	}
    	return "";
    }
    
    
    /**
     * 获取文件路径的文件名称
     * @author Defender
     * 2013-7-10 下午08:14:42
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath){
    	return filePath.substring(filePath.lastIndexOf(separator)+1,filePath.length());
    }
    public static String getOnlyFileName(String filePath){
    	String filename = filePath.substring(filePath.lastIndexOf(separator)+1,filePath.length());
    	int index = filename.lastIndexOf(".");
    	if(index>-1){
    		filename = filename.substring(0, index);
    	}
    	return filename;
    }
    
    /**
     * 创建文件
     * @author Defender
     * 2013-7-10 下午08:15:04
     * @param filePath
     * @return
     * @throws Exception
     */
    public static boolean createFile(String filePath) throws Exception {
    	return createFile(getParentPath(filePath),getFileName(filePath));
    }
    
	/**
	 * 拷贝文件
	 * 
	 * @param src
	 *            源文件
	 * @param dst
	 *            目标文件
	 * @throws Exception 
	 */
	public void copyFile( File src, File dst) throws Exception {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(dst);
			in = new FileInputStream(src);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String dstpath = dst.getAbsolutePath();
			if (dstpath.lastIndexOf("/") != -1) {
				dstpath = dstpath.subSequence(0, dstpath.lastIndexOf("/"))
						.toString();
			} else {
				dstpath = dstpath.subSequence(0, dstpath.lastIndexOf("\\"))
						.toString();
			}
			createDir(dstpath);
			copyFile(src, dst);
		} finally {
			if (null != in) {
				try {
					in.close();
					in = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
					out = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	 
    
	/**
	 * 只能删除指定的文件或者指定的空文件夹
	 * @author Defender
	 * 2013-7-10 下午08:26:11
	 * @param files
	 * @return
	 */
	public static boolean delete(File... files) {
		boolean flag =  false;
		if (files == null) {
			return flag;
		}
		for (File f : files) {
			flag = delete(f);
		}
		return flag;
	}
	
	/**
	 * 只能删除指定的文件或者指定的空文件夹
	 * @author Defender
	 * 2013-7-10 下午08:26:16
	 * @param filePaths
	 * @return
	 */
	public static boolean delete(String... filePaths) {
		boolean flag =  false;
		if (filePaths == null) {
			return flag;
		}
		int size = filePaths.length;
		File []files = new File[size];
		int i = 0;
    	for (String filePath : filePaths) {
    		files[i] = new File(filePath);
    		i++;
		}
    	return delete(files);
	}
	

	/**
	 * 删除文件及文件夹
	 * @author Defender
	 * 2013-7-10 下午08:30:58
	 * @param file
	 * @return
	 */
	public static boolean delete(File file) {
		boolean flag = false;
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				flag = file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File[] files = file.listFiles(); // 声明目录下所有的文件 files[];
				if(files!=null){
					for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
						flag = delete(files[i]); // 把每个文件 用这个方法进行迭代
					}
				}
			}
		}  
		return flag;
	}
	
	
	/**
	 * 删除文件及文件夹
	 * @author Defender
	 * 2013-7-10 下午08:34:23
	 * @param filePath
	 * @return
	 */
	public static boolean delete(String filePath) {
		File file = new File(filePath);
		return delete(file);
	}
	
	
	/**
	 * 关闭输入流
	 * @author Defender
	 * 2013-7-10 下午08:39:14
	 * @param is
	 */
	public static void close(InputStream is){
		try {
			if (is != null) {
				is.close();
				is = null;
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static void close(Reader is){
		try {
			if (is != null) {
				is.close();
				is = null;
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static void close(Writer is){
		try {
			if (is != null) {
				is.close();
				is = null;
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 关闭输出流
	 * @author Defender
	 * 2013-7-10 下午08:39:37
	 * @param out
	 */
	public static void close(OutputStream out){
		try {
			if (out != null) {
				out.close();
				out = null;
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	

	/**
	 * 获取目录下所有文件
	 * @param folder
	 * @return
	 */
	public static List<File> getFiles(String folder){
		File file=new File(folder);
		List<File> files=new ArrayList<File>();
		if (file.exists()) {
			File[] sonFiles=file.listFiles();
			if (sonFiles!=null && sonFiles.length>0) {
				for (int i = 0; i < sonFiles.length; i++) {
					if (!sonFiles[i].isDirectory()) {
						files.add(sonFiles[i]);
					}
				}
			}
		}
		return files;
	}
	/**
	 * 获取目录下所有文件夹
	 * @param folder
	 * @return
	 */
	public static List<File> getFolders(String folder){
		File file=new File(folder);
		List<File> files=new ArrayList<File>();
		if (file.exists()) {
			File[] sonFiles=file.listFiles();
			if (sonFiles!=null && sonFiles.length>0) {
				for (int i = 0; i < sonFiles.length; i++) {
					if (sonFiles[i].isDirectory()) {
						files.add(sonFiles[i]);
					}
				}
			}
		}
		return files;
	}
	/**
	 * 判断是否有子目录
	 * @param folder
	 * @return
	 */
	public static boolean hasSonFolder(String folder){
		File file = new File(folder);
		return hasSonFolder(file);
	}
	/**
	 * 判断是否有子目录
	 * @param folder
	 * @return
	 */
	public static boolean hasSonFolder(File file){
		boolean flag = false;
		if (file.exists()) {
			File[] sonFiles=file.listFiles();
			if (sonFiles!=null && sonFiles.length>0) {
				for (int i = 0; i < sonFiles.length; i++) {
					if (sonFiles[i].isDirectory()) {
						flag =  true;
						break;
					}
				}
			}
		}
		return flag;
	}
	
	/**
	 * 复制文件
	 * @param src
	 * @param dst
	 */
	public  static boolean copy(File src, File dst) {
		    boolean success = false;
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
				success = true;
			}catch (Exception e) {
				e.printStackTrace();
			} finally {
				FileUtil.close(in);
				FileUtil.close(out);
			}
			return success;
	}
	

	/**
	 * 复制文件
	 * 
	 * @param srcFilePath
	 *            源文件路径
	 * @param desFilePath
	 *            目标文件路径
	 */
	public static void copy(String srcFilePath, String desFilePath) {
		File srcFile = new File(srcFilePath);
		File desFile = new File(desFilePath);
		copy(srcFile, desFile);
	}
	 /**
     * 复制文件夹
     * @param sourceDir
     * @param targetDir
     * @throws IOException
     */
    public static boolean copyDirectiory(String sourceDir, String targetDir) throws IOException {
    	boolean success = false;
    	// 新建目标目录
    	File targetFolder = new File(targetDir);
    	if (!targetFolder.exists()) {
			targetFolder.mkdirs();
		}
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new File(new File(targetDir).getAbsolutePath() + separator + file[i].getName());
                copy(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String dir1 = sourceDir + FileUtil.separator + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + FileUtil.separator + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
            success = true;
        }
    	return success;
    }
	

	/**
	 * 功 能: 拷贝文件(只能拷贝文件)
	 * 
	 * @param strSourceFilePath
	 *            指定的文件全路径名
	 * @param strDestDir
	 *            拷贝到指定的文件夹
	 * @return 如果成功true;否则false
	 */
	public static boolean copyTo(String strSourceFilePath, String strDestDir) {
		File fileSource = new File(strSourceFilePath);
		File fileDest = new File(strDestDir);
        boolean flag = false;
		// 如果源文件不存或源文件是文件夹
		if (!fileSource.exists() || !fileSource.isFile()) {
	 		return false;
		}

		// 如果目标文件夹不存在
		if (!fileDest.isDirectory() || !fileDest.exists()) {
			if (!fileDest.mkdirs()) {
	 			return false;
			}
		}
		FileInputStream fileInput = null;
		FileOutputStream fileOutput = null;
		try {
			String strAbsFilename = strDestDir + FileUtil.separator + fileSource.getName();
			fileInput = new FileInputStream(strSourceFilePath);
			fileOutput = new FileOutputStream(strAbsFilename);
        	int count = -1;
			long nWriteSize = 0;
			long nFileSize = fileSource.length();
			byte[] data = new byte[BUFFER_SIZE];
			while (-1 != (count = fileInput.read(data, 0, BUFFER_SIZE))) {
				fileOutput.write(data, 0, count);
				nWriteSize += count;
				long size = (nWriteSize * 100) / nFileSize;
				long t = nWriteSize;
				String msg = null;
				if (size <= 100 && size >= 0) {
					msg = "\r拷贝文件进度:   " + size + "%   \t" + "\t   已拷贝:   " + t;
	 			} else if (size > 100) {
					msg = "\r拷贝文件进度:   " + 100 + "%   \t" + "\t   已拷贝:   " + t;
	 			}
				System.out.println(msg);
			}
			flag = true; 
		} catch (Exception e) {
			flag = false; 
			e.printStackTrace();
		}finally{
			FileUtil.close(fileInput);
			FileUtil.close(fileOutput); 
		}
		return flag;
	}

	

	/** 移动文件(只能移动文件)
	 * 
	 * @param strSourceFileName
	 *            是指定的文件全路径名
	 * @param strDestDir
	 *            移动到指定的文件夹中
	 * @return 如果成功true; 否则false
	 */
	public boolean moveFile(String strSourceFileName, String strDestDir) {
		if (copyTo(strSourceFileName, strDestDir)){
			return FileUtil.delete(strSourceFileName);
		}
		else{
			return false;
		}
			
	}
	
	
	/**
	 * 获取扩展名(有“.”)
	 */
	public static String getExt(File src){
		return getExt(src.getName());
	}
	
	
	/**
	 * 获取扩展名(有“.”)
	 */
	public static String getExt(String src){
		if(src==null){
			return "";
		}
		int index = src.lastIndexOf(".");
		if (index == -1
				|| index== src.length() - 1) {
			return "";
		}
		return src.substring(index,src.length());
	}
	

	 /**
	  * 得到文件后缀名
	  * @author lisheng
	  * @version v1.0
	  * @param pathOrName  文件名或文件路径
	  * @return 后缀名
	  */
	 public static String getFileSuffixName(String pathOrName) {
		 if(pathOrName==null||"".equals(pathOrName.trim())){
				return null;
		 }
		  if (pathOrName!=null&&!"".equals(pathOrName.trim())) {
				    int length = pathOrName.length();
			        int pos = pathOrName.lastIndexOf(".");
			        if(pos<0||length==pos){
			        	return "unknow";
			        }
			        return pathOrName.substring(pos+1);
		  }
		  return "unknow";
	 }
	 
	 
	 /**
	  * 得到文件后缀名
	  * @author lisheng
	  * @version v1.0
	  * @param file  文件
	  * @return 后缀名
	  */
	 public static String getFileSuffixName(File file) {
		 if(file==null){
				return null;
		 }
		  if (file.isDirectory()){
		      return "unknow";
		  }
		  String fileName = file.getName();
		  int length = fileName.length();
	        int pos = fileName.lastIndexOf(".");
	        if(fileName.equals("")||pos<0||length==pos){
	        	return "unknow";
	        }
	        return fileName.substring(pos+1);
	 }
	 

	 /**
	  * 将给定的内容输出到指定的文件
	  * @author lisheng
	  * @version v1.0
	  * @param content 内容
	  * @param file文件
	  * @throws IOException
	  */
	 public static boolean writeStringToFile(String content, File file)
	                               throws IOException {
		 if(file==null||content==null||"".equals(content.trim())){
				return false;
		 }
	       FileUtils.writeStringToFile(file, content);
	       return true;
	 }
	
	 /**
	  * 读取文件的内容
	  * @author lisheng
	  * @version v1.0
	  * @param file  文件
	  * @return 文件内容
	  * @throws Exception
	  */
	 public static String readFileToString(File file) throws Exception {
	      return FileUtils.readFileToString(file);
	 }
	 
	 

	 /**
	  * 得到指定的http url的HTML,保存到指定路径
	  * @author lisheng
	  * @version v1.0
	  * @param file  保存文件
	  * @param httpurl 网址
	  * @throws IOException
	  */
	 public static boolean writeToFileByURL(File file, String httpurl)
	                     throws IOException {
		  if(file==null||httpurl==null||"".equals(httpurl.trim())){
				return false;
		  }
	      return writeStringToFile(getStringByHTTPURL(httpurl), file);
	 }
	
	 
	 /**
	  * 得到给定网址的html内容
	  * @author lisheng
	  * @version v1.0
	  * @param httpurl 网址
	  * @return 结果HTML
	  */
	 public static String getStringByHTTPURL(String httpurl) {
		 if(httpurl==null||"".equals(httpurl.trim())){
					return "";
		 }
		  StringBuilder sb = new StringBuilder();
		  HttpURLConnection con = null;
		  URL url = null;
		  BufferedReader reader = null;
		  try {
			   url = new URL(httpurl);
			   con = (HttpURLConnection) url.openConnection();
			   // 可设置编码
			   reader = new BufferedReader(
					   new InputStreamReader(con.getInputStream()));
			   String line = null;
			   while ((line = reader.readLine()) != null){
			       sb.append(line);
			   }
		  } catch (Exception e) {
		       e.printStackTrace();
		  } finally {
			  FileUtil.close(reader);
			  url = null;
		      if (con != null){
		          con.disconnect();
		          con = null;
		      }
		  }
		  return sb.toString();
	 }
	 
	 
	 
	/**
	 * 获取字节数
	 * @author Defender
	 * 2013-7-10 下午10:10:06
	 * @param sub
	 * @return
	 */
	private static int getEncodingByteLen(String sub) {
		int zhLen = (sub.getBytes().length - sub.length()) * 2;
		int enLen = sub.length() * 2 - sub.getBytes().length;
		return zhLen + enLen;
	}
	
	/**
	 * 限制名字的长度
	 * @author Defender
	 * 2013-7-10 下午10:10:02
	 * @param str
	 * @param limit
	 * @return
	 */
	private static String subStr(String str, int limit) {
		String result = str.substring(0, 17);
		int subLen = 17;
		for (int i = 0; i < limit; i++) {
			if (limit < getEncodingByteLen(str.substring(0, (subLen + i) > str
					.length() ? str.length() : (subLen)))) {
				result = str.substring(0, subLen + i - 1);
				break;
			}
			if ((subLen + i) > str.length()) {
				result = str.substring(0, str.length() - 1);
				break;
			}
		}
		return result;
	}
	

	/**
	 * 获取目录下的所有文件（包含子目录的文件）
	 * @param directorie
	 * @return
	 */
	public static List<File> getFilesOfDir(File directorie) {
		List<File> fileList = new ArrayList<File>();
		File[] files = directorie.listFiles();
		int length = files.length;
		for (int i = 0; i < length; i++) {
			File file = files[i];
			// 判断是文件还是目录
			if (file.isDirectory()) {
				fileList.addAll(getFilesOfDir(file));
			} else {
				fileList.add(file);
			}
		}
		return fileList;
	}
	

	/**
	 * 获取目录下的所有文件（包含子目录的文件）
	 * 
	 * @param path
	 * @return
	 */
	public static List<?> getFilesOfDir(String path) {
		return getFilesOfDir(new File(path));
	}
	/**
	 * 获取指定目录下的文件名列表
	 * 参数：文件目录（绝对目录）
	 * @return 文件名列表数组
	 */
    public List<String> getFileNameList(String directory) {
    	List<String> list = new ArrayList<String>();
    	String[] fileList = new File(directory).list();
    	if(fileList!=null){
            for(String fileName : fileList){
            	String file = directory+separator+fileName;
            	if( new File(file).isFile() ){
            		list.add(fileName);
            	}
            }
    	}
		return list;
    }
    
	/**
	 * 获取指定目录下的文件目录列表
	 * 参数：文件目录（绝对目录）
	 * @return 文件目录列表数组
	 */
    public List<String> getChildDirectoryList(String directory) {
    	List<String> list = new ArrayList<String>();
        String[] fileList = new File(directory).list();  
        if(fileList!=null){
            for(String fileName : fileList){
            	String file = directory+separator+fileName;
            	if( new File(file).isDirectory() ){
            		list.add(file);
            	}
            }
        }
		return list;
    }
     

    /**
     * 根据文件名关键字(忽略大小写，空格分隔)搜索指定目录下的文件名
     * @param args
     * @throws IOException
     */
    public Map<String, String> searchFileByNameKey(String directory, String fileNameKey) {
    	Map<String, String> map = null;
		if(fileNameKey==null){
			return null;
		}
		fileNameKey = fileNameKey.trim();
		//匹配文件名
		if (!"".equals(fileNameKey)) {
			map = new HashMap<String,String>(); 
			String keys[] = fileNameKey.split("\\s");
			//在指定文件目录下，逐个匹配
			String[] fileList = new File(directory).list();
	        for(String keyStr : keys ){
	        	System.out.println(keyStr); //逐个输出数组元素的值
	        	
				for (String file : fileList) {
		             System.out.println(file); //逐个输出数组元素的值
		             if( file.toLowerCase().indexOf(keyStr.toLowerCase())>=0 ){ //匹配
		         		//map.put(file, map.get(file));
		        		if(map.get(file)==null){
		        			map.put(file, String.valueOf(1));
		        		}else{
		        			map.put(file, String.valueOf(Integer.parseInt(map.get(file))+1) );
		        		}
		             }
		        }
	        }
		}
		return map;
    }   
    
    /**
     * 根据文件更新时间关键字(忽略大小写，空格分隔)搜索指定目录下的文件名
     * @param args
     * @throws IOException
     */
    public Map<String, String> searchFileByTimeKey(String directory, String updateTimeKey) {
    	Map<String, String> map = null;
		if(updateTimeKey==null){
			return null;
		}
		updateTimeKey = updateTimeKey.trim();
		//匹配文件名
		if (!"".equals(updateTimeKey.trim())) {
			map = new HashMap<String,String>(); 
			String keys[] = updateTimeKey.split("\\s");
			
			//在指定文件目录下，逐个匹配
			File[] fileList = new File(directory).listFiles();//指定目录下的所有文件名
			
			//long modifyDate = file.lastModified();   //得到最后修改日期
			
	        for(String keyStr : keys ){
	        	System.out.println(keyStr); //逐个输出数组元素的值
				for (File file : fileList) {
					 String updateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified());
		             if( updateTime.indexOf(keyStr.toLowerCase())>=0 ){ //匹配
		         		//map.put(file, map.get(file));
		        		if(map.get(file.getName())==null){
		        			map.put(file.getName(), String.valueOf(1));
		        		}else{
		        			map.put(file.getName(), String.valueOf(Integer.parseInt(map.get(file))+1) );
		        		}
		             }
		        }
	        }
		}
		return map;
    }   
    
    /**
	  * 根据指定的文件绝对路径得到文件大小字符串
	  * @author lisheng
	  * @version v1.0
	  * @param file文件
	  * @return 文件大小字符串
	  */
	 public static String getFileSize(File file) {
		  if (file.isDirectory()){
		     return "-";
		  }
		  double size = file.length();
		  if (size >= 0 && size < 1024){
		     return file.length() + "Byte";
		  }
		  if (size >= 1024 && size < 1024 * 1024){
		     return formatNumber(size / 1024, 2, 2) + "KB";
		  }
		  return formatNumber(size / 1024 * 1024, 2, 2) + "MB";
	 }
	 

	 /**
	  * 得到数字格式化后的字符串
	  * @author lisheng
	  * @version v1.0
	  * @param numberNumber类型
	  * @param minFractionDigits小数最小位数
	  * @param maxFractionDigits小数最大位数
	  * @return String 格式化后的字符串
	  */
	 private static String formatNumber(Number number, int minFractionDigits,
	                                    int maxFractionDigits) {
		  NumberFormat format = NumberFormat.getInstance();
		  format.setMinimumFractionDigits(minFractionDigits);
		  format.setMaximumFractionDigits(maxFractionDigits);
		  return format.format(number);
	 } 



		/**
		 * Gets file extension.
		 *
		 * @param fileName name of file.
		 * @return file extension
		 */
		public static String getFileExtension(final String fileName, final boolean shortExtensionMode) {
			if (shortExtensionMode) {
				return FileUtil.getFileExtension(fileName);
			}
			int index = fileName.lastIndexOf(".");
			if (fileName == null
					|| index == -1
					|| index == fileName.length() - 1) {
				return null;
			}
			return fileName.substring(index + 1);
		}

		/**
		 * Gets file last extension.
		 *
		 * @param fileName name of file.
		 * @return file extension
		 */
		public static String getFileExtension(final String fileName) {
			int index = fileName.lastIndexOf(".");
			if (fileName == null
					|| index == -1
					|| index== fileName.length() - 1) {
				return null;
			}
			return fileName.substring(index + 1);
		}

		/**
		 * Gets file name without it's extension.
		 *
		 * @param fileName name of file
		 * @return file extension
		 */
		public static String getFileNameWithoutExtension(final String fileName, final boolean shortExtensionMode) {
			if (shortExtensionMode) {
				return FileUtil.getFileNameWithoutExtension(fileName);
			}

			if (fileName == null || fileName.indexOf(".") == -1) {
				return null;
			}
			return fileName.substring(0, fileName.indexOf("."));
		}

		/**
		 * Gets file name without it's last extension.
		 *
		 * @param fileName name of file
		 * @return file extension
		 */
		public static String getFileNameWithoutExtension(final String fileName) {
			if (fileName == null || fileName.lastIndexOf(".") == -1) {
				return null;
			}
			return fileName.substring(0, fileName.lastIndexOf("."));
		}
		
		/**
		 * if file exists this method adds (number) to file.
		 *
		 * @param path folder
		 * @param name file name
		 * @return new file name.
		 */
		public static String getFinalFileName(final String parent, final String name) {
			File file = new File(parent, name);
			int number = 0;

			String nameWithoutExtension = getFileNameWithoutExtension(name, false);
			Pattern p = Pattern.compile("^(AUX|COM\\d|CLOCK\\$|CON|NUL|PRN|LPT\\d)$", Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(nameWithoutExtension);
			boolean protectedName = m.find() ? true : false;
			String newFileName = name;
			while (true) {
				if (file.exists() || protectedName) {
					number++;
					StringBuilder sb = new StringBuilder();
					sb.append(getFileNameWithoutExtension(name, false));
					sb.append("(").append(number).append(").");
					sb.append(getFileExtension(name, false));
					newFileName = sb.toString();
					file = new File(parent, newFileName);
					protectedName = false;
				} else {
					return newFileName;
				}
			}
		}
}
